package com.webchat.pgc.config;


import com.webchat.common.constants.WebConstant;
import com.webchat.common.enums.RedisKeyEnum;
import com.webchat.common.service.RedisService;
import com.webchat.pgc.messagequeue.task.PgcMessageQueueTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class ScheduleConfig {

    @Autowired
    private RedisService redisService;

    @Autowired
    private PgcMessageQueueTaskService pgcMessageQueueTaskService;

    /**
     *  处理当前wenchat PGC 服务下失败的mq任务
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void handleFailMQTaskSchedule() {

        // 加锁
        RedisKeyEnum lockEnum = RedisKeyEnum.SCHEDULE_HANDLER_FAIL_MQ_TASK_PGC_LOCK;

        doExecScheduleTask(lockEnum, () -> {
            pgcMessageQueueTaskService.doExecute();
        });
    }

    private void doExecScheduleTask(RedisKeyEnum lockEnum, Runnable runnable, boolean ... releaseLock) {
        boolean lockRes = redisService.installDistributedLock(lockEnum.getKey(), WebConstant.CACHE_NONE, lockEnum.getExpireTime());
        if (!lockRes) {
            // 当前节点未获取MQ失败任务处理锁资源，由集群其他获取到当前lock节点来执行调度
            return;
        }
        runnable.run();
        if (releaseLock.length > 0 && releaseLock[0]) {
            redisService.releaseDistributedLock(lockEnum.getKey(), WebConstant.CACHE_NONE);
        }
    }
}
